package com.example.eci_quartz.cloudcc.impl;

import com.example.eci_quartz.cloudcc.commcon.CommonMethod;
import com.example.eci_quartz.cloudcc.commcon.DataGroupUtil;
import com.example.eci_quartz.cloudcc.commcon.DateUtil;
import com.example.eci_quartz.cloudcc.dao.DefaultConnectionFactory;
import com.example.eci_quartz.cloudcc.dao.baseDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 *同步设备信息下CSA
 */
public class CsaImpl extends baseDao {
	SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
	SimpleDateFormat sdfY= new SimpleDateFormat("yyyy");
	SimpleDateFormat sdfM= new SimpleDateFormat("MMdd");
	static String binding = InsertXMInfo();
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String upsertCsa(){
		Connection conn =null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Map> updatelist =null;
		List<Map> insertlist =null;

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		Calendar cal=Calendar.getInstance();
	    cal.set(Calendar.DATE,cal.get(Calendar.DATE)-30);
	    String firstDay=format.format(cal.getTime());
          //获取系统当天时间
        String newDate=format.format(new Date());

		String info = "false";
		String orderinfo = "";//查询返回来的值
		String order_datas = "";//查询成功返回来的数据
		Map<String, Map> orderMap=null;
		Map<String,Map> rsMap=null;
		String sql="select * FROM LIBJ49FSMS.CSANEW ";
				//+" WHERE ENTDT8 BETWEEN '"+firstDay+"' AND '"+newDate+"' OR CHGDT8 BETWEEN '"+firstDay+"' AND '"+newDate+"' ";
		int count=1;
		try {
			conn = new DefaultConnectionFactory().getConnection();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			rsMap=new HashMap<String,Map>();//map<零件号，零件数据>从DBS查询出来的
			orderMap = new HashMap<String, Map>();// map<销售订单编号，销售订单对象值>
			String codes="";//项目编号数组
			String sns="";//设备数组
			if (rs != null) {
				while (rs.next()) {
					Map mapObj=new HashMap();
					//CSA编码
					//String name=(rs.getString("SCEN") == null ? "" : rs.getString("SCEN")+ "").trim();
					String name=(rs.getString("AGRNO") == null ? "" : rs.getString("AGRNO")+"").trim();
					//设备序列号
					String sn=(rs.getString("EQMFSN") == null ? "" : rs.getString("EQMFSN")+ "").trim();
					if(sn!=null&&!"".equals(sn)){
						mapObj.put("sn",sn);
					}
					//开始时间
					String ksrq=(rs.getString("FDATE8") == null ? "" : rs.getString("FDATE8")+ "").trim();
			        mapObj.put("ksrq",DateUtil.getDatetoStringUtil((rs.getString("FDATE8") == null ? "" : rs.getString("FDATE8")+ "").trim()));
			        mapObj.put("sfjktb", 1);
			        //结束时间
			        String jsrq=(rs.getString("TDATE8") == null ? "" : rs.getString("TDATE8")+ "").trim();
			        mapObj.put("jsrq",DateUtil.getDatetoStringUtil((rs.getString("TDATE8") == null ? "" : rs.getString("TDATE8")+ "").trim()));
					//年限(csa结束时间-csa开始时间 天)
					if((ksrq!=null && !"".equals(ksrq))&&(jsrq!=null && !"".equals(jsrq))){
						String nx=String.valueOf(Integer.parseInt(jsrq)-Integer.parseInt(ksrq));
						if(nx!=null&&!"".equals(nx)) {
							mapObj.put("csanx", nx.substring(0, 1));
						}
					}
					//类型--小时数
					mapObj.put("xss", (rs.getString("AGRDSC") == null ? "" : rs.getString("AGRDSC")+ "").trim());
					//客户编码
					//mapObj.put("khbh", (rs.getString("CUNO1") == null ? "" : rs.getString("CUNO1")+ "").trim());
					mapObj.put("CUNO3", (rs.getString("CUNO3") == null ? "" : rs.getString("CUNO3")+ "").trim());
					//工单类型
					mapObj.put("CUPONO", (rs.getString("CUPONO") == null ? "" : rs.getString("CUPONO")+ "").trim());
					//创建时间
					mapObj.put("dbscjsj", DateUtil.getDatetoStringUtil((rs.getString("ENTDT8") == null ? "" : rs.getString("ENTDT8")+ "").trim()));
					//修改时间
					mapObj.put("dbsxgsj", DateUtil.getDatetoStringUtil((rs.getString("CHGDT8") == null ? "" : rs.getString("CHGDT8")+ "").trim()));
					String code="";
					if(name!=null&&!"".equals(name)&&(sn!=null&&!"".equals(sn))) {
						//唯一编码
						code=name;
						mapObj.put("name",code);
						//项目编号数组
						codes+="'"+code+"',";
						//设备数组
						sns+="'"+sn+"',";
						rsMap.put(code, mapObj);
					}
			}
			String result="";
			 //判断是否存在
		     if(codes!=null&&!"".equals(codes)){
					//查询系统中全部的标准工时
					String data_query = "serviceName=cqlQuery&objectApiName=csa" +
							"&expressions=select id,name from csa  " +
							"where name is not null and name in ("+codes.substring(0, codes.length()-1)+")  " +
							"and is_deleted='0'&binding=";//查询设备信息
					orderinfo = operate(data_query+ binding);
					//判断binding是否失效，如果失效，就重新获取
				    JSONObject fromObject =null;
					if(CommonMethod.isJSONValid(orderinfo)){
						fromObject = JSONObject.fromObject(orderinfo);
						result= fromObject.getString("result")==null?"":fromObject.getString("result");
					}
					if(!"true".equals(result)){
						binding = InsertXMInfo();
						orderinfo=operate(data_query+binding);
						fromObject = JSONObject.fromObject(orderinfo);
						if(CommonMethod.isJSONValid(orderinfo)){
							fromObject = JSONObject.fromObject(orderinfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
					}
					String returninfo = "[" + orderinfo + "]";// 手动转换成json格式，方便取值
					if (!"[]".equals(returninfo)&&orderinfo!=null) {
						JSONArray brand_list = JSONArray.fromObject(returninfo);
						if (brand_list != null) {
							for (int j = 0; j < brand_list.size(); j++) {
								JSONObject brandInfo = (JSONObject) brand_list.get(j);
								String Result = brandInfo.get("result") == null?"":brandInfo.get("result")+"";// 获取返回值
								String date = brandInfo.get("data") == null?"":brandInfo.get("data")+"";// 获取返回值
								if ("true".equals(Result)) {
									order_datas = date;
								}
							}
						}
					}
					// 查询CRM系统中PIP&PSP的信息并存入到map中
					if (order_datas!= "[]"&&!"".equals(order_datas)) {
						JSONArray datas_list = JSONArray.fromObject(order_datas);
						if (datas_list != null) {
							for (int i = 0; i < datas_list.size(); i++) {
								JSONObject accObj = (JSONObject) datas_list.get(i);
								JSONObject order_newObj = new JSONObject();//新的json，只存id，编号
								//设备编号
							    String code= (accObj.get("name")==null? "" : accObj.get("name").toString()).trim();
							    if(code!=null&&!"".equals(code)){
							    	order_newObj.put("id", accObj.get("id"));
									order_newObj.put("name", code);
									orderMap.put(code,order_newObj);
							    }
							}
						}
					}
			  }
			//判断零件是新增还是更新
			if(rsMap.size()>0&&rsMap!=null){
				updatelist = new ArrayList<Map>();
				insertlist = new ArrayList<Map>();
				Map  sbMaps=EquipmentImpl.getsbglMap(sns);	//查询设备集合
			   for(String code:rsMap.keySet()){
				    Map ljObj=rsMap.get(code);//获取DBS中的客户数据
				  // if(orderMap!=null&&orderMap.size()>0){
					   if (orderMap.containsKey(code)) {// 更新设备信息
						   Map casMap =orderMap.get(code);
						   Map  sbMap=(Map)sbMaps.get(ljObj.get("sn"));
						   if(sbMap!=null&&!"".equals(sbMap)) {
							   ljObj.put("sbxlh", (sbMap.get("id") == null ? "" : sbMap.get("id")+ "").trim());
						   }
						   ljObj.put("id",casMap.get("id"));
						   updatelist.add(ljObj);
						}else {// 新建设备信息
							 Map  sbMap=(Map) sbMaps.get(ljObj.get("sn"));
							   if(sbMap!=null&&!"".equals(sbMap)) {
								   ljObj.put("sbxlh", (sbMap.get("id") == null ? "" : sbMap.get("id")+ "").trim());
							   }
							insertlist.add(ljObj);
						}
					// }
				}
			}
			//插入新的CSA信息
			if (insertlist!=null&&insertlist.size()> 0) {
				Map<Integer,List> map = DataGroupUtil.dataOneGroup(insertlist); //用map存起来新的分组后数据,每100条一组
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayInsert = JSONArray.fromObject(amList);
						String jsonstr=jsonArrayInsert.toString();
						jsonstr = java.net.URLEncoder.encode(jsonstr, "UTF-8");
						String data_insert = "serviceName=insert&objectApiName=csa&data="+jsonstr+"&binding=";
			            String insertInfo=operate(data_insert+ binding);//执行CRM系统插入操作insert

						//判断binding是否失效，如果失效，就重新获取
					    JSONObject fromObject =null;
						if(CommonMethod.isJSONValid(orderinfo)){
							fromObject = JSONObject.fromObject(orderinfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){
							binding = InsertXMInfo();
							insertInfo=operate(data_insert+binding);
						}
					    info="insert_success";
					}
				}
			}
			//更新系统中的设备信息
			if (updatelist!=null&&updatelist.size() > 0) {
				Map<Integer,List> map = DataGroupUtil.dataGroup(updatelist);
				if(map.size()>0){
					for(Integer m:map.keySet()){
						List amList=map.get(m);
						JSONArray jsonArrayUpdate = JSONArray.fromObject(amList);
						String jsonstr_update=jsonArrayUpdate.toString();
						jsonstr_update = java.net.URLEncoder.encode(jsonstr_update, "UTF-8");
						String data_update = "serviceName=updateLt&objectApiName=csa" +
								"&data="+jsonstr_update+"&binding=";//updateLt批量更新，不走触发器
			           String updateInfo= operate(data_update+binding);//执行CRM更新操作update
						//判断binding是否失效，如果失效，就重新获取
					    JSONObject fromObject =null;
						if(CommonMethod.isJSONValid(updateInfo)){
							fromObject = JSONObject.fromObject(updateInfo);
							result= fromObject.getString("result")==null?"":fromObject.getString("result");
						}
						if(!"true".equals(result)){
							binding = InsertXMInfo();
							updateInfo=operate(data_update+binding);
						}
			            info="update_success";
					}
				}
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (pstmt != null) {
					pstmt.close();
					pstmt = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return info;
	}

}
